﻿package com.shuqi.model.parse.parser;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import com.shuqi.common.utils.Util;

/**
 * 解析xml主要类
 * 
 * @author jinliang
 * @since before 5.0
 */
public class XMLHelper {

    /**
     * @Des 描述 判断isEPUB
     * @author Tim
     * @param handler
     * @param u
     * @throws IOException
     * @throws SAXException void
     */

    public static boolean isEPUB(DefaultHandler handler, String u) throws IOException, SAXException {
        /* 本地xml文件(仅EPUB阅读页用到) */
        if (u != null && !u.startsWith("http")) {
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(u);
                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser parser = factory.newSAXParser();
                XMLReader reader = parser.getXMLReader();
                reader.setContentHandler(handler);
                reader.parse(new InputSource(fileInputStream));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (FactoryConfigurationError e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                throw e;
            } finally {
                if (fileInputStream != null) {
                    fileInputStream.close();
                    fileInputStream = null;
                }
            }
            return true;
        } else
            return false;
    }

    /** 直接读Inputstream */
    public static void doInputSteamParse(DefaultHandler handler, ByteArrayInputStream is) {
        doInputSourceParse(handler, new InputSource(is));
    }
    
    /** 直接读InputSource */
    private static void doInputSourceParse(DefaultHandler handler, InputSource isputSource) {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            reader.setContentHandler(handler);
            if (isputSource != null) {
                reader.parse(isputSource);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 
}
